package ui.listeners;

import java.io.File;
import java.io.IOException;

import org.apache.pivot.io.FileList;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtk.DropAction;
import org.apache.pivot.wtk.DropTarget;
import org.apache.pivot.wtk.Manifest;

import ui.window.MDKWindow;

public class DragDropFileListener {
	
	private MDKWindow window;
	
	public DragDropFileListener(MDKWindow mdkwindow){
		this.window = mdkwindow;
		
		window.setDropTarget(new DropTarget() {

			
			public DropAction dragEnter(Component component, Manifest dragContent,
                int supportedDropActions, DropAction userDropAction) {
                DropAction dropAction = null;

                if (dragContent.containsFileList()
                    && DropAction.COPY.isSelected(supportedDropActions)) {
                    dropAction = DropAction.COPY;
                }

                return dropAction;
            }

			
			public void dragExit(Component arg0) {
				// TODO Auto-generated method stub
				
			}

			
			public DropAction dragMove(Component component, Manifest dragContent,
                int supportedDropActions, int x, int y, DropAction userDropAction) {
                return (dragContent.containsFileList() ? DropAction.COPY : null);
            }

			
			public DropAction drop(Component component, Manifest dragContent,
	                int supportedDropActions, int x, int y, DropAction userDropAction) {
	            DropAction dropAction = null;
	            if (dragContent.containsFileList()) {
	                try {
	                    FileList fileList = dragContent.getFileList();
	                    for (File file : fileList) {
	                        if (file.isDirectory()) {
	                            // TODO Expand recursively
	                        }
	                        else
	                        {
	                        	window.loadFile(file);
	                        }
	                    }
	
	                    dropAction = DropAction.COPY;
	                } catch(IOException exception) {
	                    System.err.println(exception);
	                }
	            }
	
	            dragExit(component);

	            return dropAction;
			}

			
			public DropAction userDropActionChange(Component component, Manifest dragContent,
                int supportedDropActions, int x, int y, DropAction userDropAction) {
                return (dragContent.containsFileList() ? DropAction.COPY : null);
            }
           
		});
	}
}
